package com.useeinfo.oa.modules.task.dao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.dao.CrudDao;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.QueryUtils;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.NumberUtil;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Organization;
import com.useeinfo.oa.modules.base.entity.Position;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.task.entity.TaskOrder;
import com.useeinfo.oa.modules.task.enums.TaskAssignTypeEnum;
import com.useeinfo.oa.modules.task.enums.TaskOrderStatusEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.*;

/**
 * @auther: bin.liu
 * @Date: 2019/6/25 9:30
 * @Description: 任务工单dao
 */
@Repository("taskOrderDao")
public class TaskOrderDao implements CrudDao<TaskOrder> {

    private final static Logger logger = LoggerFactory.getLogger(TaskOrderDao.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private OrganizationBiz organizationBiz;

    @Override
    public Map<String, Object> getSearchCondition(Map<String, String> queryHash){
        Map<String, Object> conditionHash = new HashMap<>();

        conditionHash.put("t.deleteStatus = ?{paramIndex} ", false);
        if (queryHash == null || queryHash.size() == 0) {
            return conditionHash;
        }

        String id = queryHash.get("id");
        if (StringUtils.isNotBlank(id)) {
            conditionHash.put("t.id = ?{paramIndex}", StringConverters.null2Long(id));
        }

        String enterpriseId = queryHash.get("enterpriseId");
        if (StringUtils.isNotBlank(enterpriseId)) {
            conditionHash.put("t.enterprise.id = ?{paramIndex}", StringConverters.null2Long(enterpriseId));
        }

        String serial = queryHash.get("serial");
        if (StringUtils.isNotBlank(serial)) {
            conditionHash.put("t.serial like ?{paramIndex} ", "%" + serial + "%");
        }

        String orderName = queryHash.get("orderName");
        if (StringUtils.isNotBlank(orderName)) {
            conditionHash.put("t.orderName like ?{paramIndex} ", "%" + orderName + "%");
        }

        String taskContent = queryHash.get("taskContent");
        if (StringUtils.isNotBlank(taskContent)) {
            conditionHash.put("t.taskContent like ?{paramIndex} ", "%" + taskContent + "%");
        }

        String orderStatus = queryHash.get("orderStatus");
        if (StringUtils.isNotBlank(orderStatus)) {
            conditionHash.put("t.taskOrderStatus = ?{paramIndex}", TaskOrderStatusEnum.valueOf(orderStatus));
        }

        String createUser = queryHash.get("createUser");
        if (StringUtils.isNotBlank(createUser)) {
            conditionHash.put("t.createUser.userName like ?{paramIndex}", "%" + createUser + "%");
        }
        String createId = queryHash.get("createId");
        if (StringUtils.isNotBlank(createId)) {
            conditionHash.put("t.createUser.id = ?{paramIndex}",  StringConverters.null2Long(createId));
        }
        String receiveUser = queryHash.get("receiveUser");
        if (StringUtils.isNotBlank(receiveUser)) {
            conditionHash.put("t.receiveUser.id = ?{paramIndex}",  StringConverters.null2Long(receiveUser));
        }

        String orderTypeName = queryHash.get("orderTypeName");
        if (StringUtils.isNotBlank(orderTypeName)) {
            conditionHash.put("t.orderType.propertyName like ?{paramIndex}", "%"+orderTypeName+"%" );
        }

        String createDate1 = queryHash.get("createDate1");
        if (StringUtils.isNotBlank(createDate1)) {
            conditionHash.put("t.createDate >= ?{paramIndex} ", DateTimeUtils.getBeginOfDay(StringConverters.ToDateOnly(createDate1)));
        }

        String createDate2 = queryHash.get("createDate2");
        if (StringUtils.isNotBlank(createDate2)) {
            conditionHash.put("t.createDate <= ?{paramIndex} ", DateTimeUtils.getEndOfDay(StringConverters.ToDateOnly(createDate2)));
        }

        String auditUserId = queryHash.get("auditUserId");
        String auditPositionId = queryHash.get("auditPositionId");
        if (StringUtils.isNotBlank(auditUserId) && StringUtils.isBlank(auditPositionId)) {
            conditionHash.put("t.auditUser.id = ?{paramIndex}", StringConverters.null2Long(auditUserId));
        } else if (StringUtils.isBlank(auditUserId) && StringUtils.isNotBlank(auditPositionId)) {
            conditionHash.put("t.auditPosition.id = ?{paramIndex}", StringConverters.null2Long(auditPositionId));
        } else if (StringUtils.isNotBlank(auditUserId) && StringUtils.isNotBlank(auditPositionId)) {
            conditionHash.put("(t.auditUser.id = ?{paramIndex} or t.auditPosition.id = " + auditPositionId + " )", StringConverters.null2Long(auditUserId));
        }

        String auditOrganizationId = queryHash.get("auditOrganizationId");
        if (StringUtils.isNotBlank(auditOrganizationId)) {
            conditionHash.put("t.auditOrganization.id = ?{paramIndex}", StringConverters.null2Long(auditOrganizationId));
        }

        return conditionHash;
    }

    //dashborad报表 工单数
    public String dashBoardInfo(String enterpriseId, String status, String date) {
        String dashHql = "select count(t.id) from TaskOrder t where t.taskOrderStatus in (" + status + ")";
        if (StringUtils.isNotBlank(enterpriseId)) {
            dashHql = dashHql + " and t.enterprise.id=" + enterpriseId;
        }
        dashHql = dashHql + " and t.createDate like '" + date + "%'";
        dashHql = dashHql + " and t.deleteStatus=false";

//        logger.info("拼接完成的sql语句为：{}",dashHql);
        Query resultQuery = this.entityManager.createQuery(dashHql);
        Object o = resultQuery.getSingleResult();
        return o.toString();
    }

    //dashboard报表
    public JSONArray getbetween(String enterpriseId, String start, String end, int type, boolean completed) {
        String dashHql = "select count(i.id),date_format(i.createDate,'%Y-%m-%d'),";//type 1小时统计，2天数统计
        if (type == 1) {
            dashHql = dashHql + "Hour(i.createDate)";
        } else {
            dashHql = dashHql + "Day(i.createDate)";
        }
        // 数据库中的数据格式是 2019-01-31 00:00:00  这里做一下日期时间拼接
        String sqlStart = start + " 00:00:00";
        String sqlEnd = end + " 23:59:59";
        dashHql = dashHql + "from TaskOrder i  where i.createDate>='" + sqlStart + "' and i.createDate <'" + sqlEnd + "'";
        if (StringUtils.isNotBlank(enterpriseId) && !enterpriseId.equals("null")) {
            dashHql = dashHql + " and i.enterprise.id = " + enterpriseId + " ";
        }
        if (completed) {
            dashHql = dashHql + " and i.taskOrderStatus = 'COMPLETED' and i.taskFinishTime >='" + start + "' and i.taskFinishTime <'" + end + "'";
        }
        dashHql = dashHql + " and i.deleteStatus=false";
        if (type == 1) {
            dashHql = dashHql + " group by hour(i.createDate)";

        } else {
            dashHql = dashHql + " group by Day(i.createDate)";
        }
//        logger.info("拼接完成的sql语句为：{}", dashHql);
        Query query = this.entityManager.createQuery(dashHql);
        List<Object> o = query.getResultList();

        return organizationBiz.getDashBoardData(o, start, end, type);
    }

    /**
     * Charts 根据人员计算工时
     */
    public List<Object> getHoursChartsData(String startDateTime, String endDateTime, String enterpriseId, String organizationId) {
        String sql = " SELECT SUM(f.working_hours) working_hours FROM " +
                "(SELECT b.id,SUM(a.working_hours) working_hours FROM task_order a " +
                " right JOIN SYSTEM_USER b " +
                " ON a.`receive_user_id` = b.id  AND a.task_finish_time > '" + startDateTime + "' AND a.task_finish_time < '" + endDateTime + "' and a.task_order_status = 'COMPLETED' " +
                " AND a.source in ('CUSTOMER_REPORT','INSPECTION_REPAIR') " +
                " AND a.delete_status = false ";
        if (StringUtils.isNotBlank(enterpriseId)) {
            sql += " AND a.`enterprise_id` = '" + enterpriseId + "' ";
        }
        sql = sql + " LEFT JOIN system_user_organization g " +
                " ON b.id = g.system_user_id " +
                " WHERE b.delete_status=false ";

        if (StringUtils.isNotBlank(organizationId)) {
            sql += " AND g.`organization_id` = " + organizationId + " ";
        }
        sql += " " +
                " GROUP BY b.`id` " +
                " UNION ALL " +
                " SELECT  d.id,SUM(c.working_hours) working_hours FROM task_order_partner c " +
                " LEFT JOIN SYSTEM_USER d " +
                " ON c.partner_id = d.id " +
                " LEFT JOIN task_order e " +
                " ON c.task_order_id = e.id " +
                " LEFT JOIN system_user_organization h " +
                " ON d.id = h.system_user_id " +
                " WHERE e.task_order_status = 'COMPLETED' " +
                " AND c.delete_status = false ";
        if (StringUtils.isNotBlank(enterpriseId)) {
            sql += " AND c.`enterprise_id` = '" + enterpriseId + "' ";
        }
        if (StringUtils.isNotBlank(organizationId)) {
            sql += " AND h.`organization_id` = " + organizationId + " ";
        }
        sql += " AND c.update_date > '" + startDateTime + "' AND c.update_date < '" + endDateTime + "' " +
                " GROUP BY d.`id`) f " +
                " GROUP BY f.id " +
                " ORDER BY f.id ";
        return entityManager.createNativeQuery(sql).getResultList();
    }

    /**
     * appdashboard 根据人员计算接单数
     *
     * @param organizationId
     * @param start
     * @param end
     * @return
     */
    public List<Object> getOrganizationReceiveNum(String organizationId, String start, String end) {
        String sql = "select COUNT(r.id),uo.system_user_id,date_format(r.receive_time,'%Y-%m-%d') as nowday,Month(r.receive_time) as nowmonth,quarter(r.receive_time)  as nowseason  from  system_user_organization uo  LEFT JOIN task_order r " +
                " on r.receive_user_id=uo.system_user_id  and r.delete_status=false and r.receive_time >= '" + start + "' AND r.receive_time <'" + end + "' and r.receive_user_id is not null  WHERE" +
                " uo.organization_id=" + organizationId + " and uo.delete_status=false  group by uo.system_user_id";
        sql = sql + " order by uo.system_user_id";
        Query query = this.entityManager.createNativeQuery(sql);
        List<Object> objects = query.getResultList();
        return objects;
    }

    public JSONArray getTags(TaskOrder taskOrder, SystemUser systemUser, String status) {
        JSONArray tags = new JSONArray();
        Date now = new Date();
        if (taskOrder.getRequireFinishTime() != null) {
            if (now.getTime() > taskOrder.getRequireFinishTime().getTime()) {
                tags.add(tagObject("逾期", "full-orange"));
            }
        }
//        else if (taskOrder.getRequirePresenceTime()!=null&&taskOrder.getPresenceTime()==null) {
//            if (now.getTime() > taskOrder.getPresenceTime().getTime()) {
//                tags.add(tagObject("逾期", "full-orange"));
//            }
//        }

        if (taskOrder.isAssign()) {
            tags.add(tagObject("被指派", "blue"));
        }
        if ("IN_AUDITING".equals(taskOrder.getTaskOrderStatus().getCode())) {
            tags.add(tagObject(NumberUtil.convert(taskOrder.getAuditLevel() + 1) + "审", "blue"));
        }
        return tags;
    }


    /**
     * 获取总记录数
     */
    @Override
    public Long totalRecord(Map<String, String> queryHash){
        Map<String, Object> conditions = getSearchCondition(queryHash);
        TypedQuery<Long> typedQuery = QueryUtils.getTypedQueryByCondition("select count(t) from TaskOrder t ", conditions, entityManager, Long.class);
        return typedQuery.getSingleResult();
    }

    /**
     * 分页列表
     */
    @Override
    public List<TaskOrder> findList(QueryParam queryParam){
        String taskOrderStatus = queryParam.getSqlMap().get("taskOrderStatus");
        String sqlInfo = "";
        if (!"IN_AUDITING".equals(taskOrderStatus)) {
            sqlInfo = queryParam.joinJPQL("select t from TaskOrder t ", "order by t.id desc ");
        } else {
            sqlInfo = queryParam.joinJPQL("select t from TaskOrder t ", "order by t.updateDate desc ");
        }


        Map<String, Object> conditions = getSearchCondition(queryParam.getSqlMap());
        TypedQuery<TaskOrder> typedQuery = QueryUtils.getTypedQueryByCondition(sqlInfo, conditions, entityManager, TaskOrder.class);
        return queryParam.findPageList(typedQuery);
    }

    /**
     * id获取记录
     */
    @Override
    public TaskOrder findModel(Long id){
        return entityManager.find(TaskOrder.class, id);
    }

    /**
     * 增加记录
     */
    @Override
    public Integer add(TaskOrder taskOrder){
        taskOrder.setCreateDate(new Date());
        entityManager.persist(taskOrder);
        logger.info("TaskOrderDaoImpl添加taskOrder成功！");
        return 1;
    }

    /**
     * 修改记录
     */
    @Override
    public Integer update(TaskOrder taskOrder){
        taskOrder.setUpdateDate(new Date());
        entityManager.merge(taskOrder);
        return 1;
    }

    /**
     * 删除记录
     */
    @Override
    public Integer delete(Long id){
        TaskOrder taskOrder = entityManager.find(TaskOrder.class, id);
        entityManager.remove(taskOrder);
        return 1;
    }

    /**
     * 删除记录 - 逻辑删除
     */
    @Override
    public Integer deleteLogic(TaskOrder taskOrder){
        taskOrder.setDeleteStatus(true);
        return 1;
    }

    /**
     * 获取任务单流水号
     *
     * @param enterpriseId
     * @return
     */
    public String getCode(String enterpriseId) {
        String code = enterpriseId + "-" + DateTimeUtils.formatDateToStringWithOnlyDate(new Date(), "yyyyMMdd") + "-" + (int) ((Math.random() * 9 + 1) * 100000);
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("serial", code);
        List<TaskOrder> taskOrders = findList(queryParam);
        if (CollectionUtils.isNotEmpty(taskOrders)) {
            return getCode(enterpriseId);
        } else {
            return code;
        }
    }

    public List<SystemUser> sendTaskUsers(TaskOrder taskOrder, Enterprise enterprise, List<Long> ids) {
        String jpql = "SELECT s FROM SystemUser s WHERE 1 = 1 " +
                " AND " + StringConverters.null2Long(enterprise.getId()) + " in elements(s.enterpriseSet) " +
                "AND s.operationRole = 'common' " +
                "AND s.deleteStatus = false ";
        if (taskOrder.isAssign()) {
            if (TaskAssignTypeEnum.USER.getCode().equals(taskOrder.getTaskAssignTypeEnum().getCode())) {
                jpql += "AND s.id in (" + StringUtils.strip(ids.toString(), "[]") + ") ";
            } else if (TaskAssignTypeEnum.POSITION.getCode().equals(taskOrder.getTaskAssignTypeEnum().getCode())) {
                if (CollectionUtils.isNotEmpty(ids)) {
                    jpql += "AND exists (SELECT a from s.positionSet a Where a.id in (" + StringUtils.strip(ids.toString(), "[]") + ")) ";
                }
            }
        }
        if (!taskOrder.isAssign() && taskOrder.getTaskArea() != null) {
            jpql += "AND " + taskOrder.getTaskArea().getId() + " in elements(s.areaSet) ";
        }
        logger.info("执行的sql语句为：{}", jpql);
        TypedQuery<SystemUser> resultQuery = this.entityManager.createQuery(jpql, SystemUser.class);
        return resultQuery.getResultList();
    }



    /**
     * 获取工单列表
     * @param pageIndex 分页参数
     * @param pageSize 分页参数
     * @param enterpriseId 企业id
     * @param userId 用户id
     * @param areaIds 区域id
     * @param positionId 岗位id
     * @param status 状态
     * @param leader 是否是主管
     * @param organization 组织
     * @param searchParam 查询参数
     * @param date 日期
     * @return JSONObject
     */
    public JSONObject getTaskOrders(String pageIndex, String pageSize, String enterpriseId, String userId, Set<Long> areaIds,
                                      String positionId, String status, boolean leader, Organization organization, String searchParam, String date) {
        JSONObject result = new JSONObject();
        int index = 0;
        int size = 0;
        if (StringUtils.isNotBlank(pageIndex)) {
            index = StringConverters.null2Int(pageIndex);
        }

        if (StringUtils.isNotBlank(pageSize)) {
            size = StringConverters.null2Int(pageSize);
        }

        String jpql = "SELECT s FROM TaskOrder s  WHERE 1 = 1 " +
                " AND s.enterprise.id = " + StringConverters.null2Long(enterpriseId) +
                " AND s.deleteStatus = false ";

        // 待接单
        if("1".equals(status)){
            jpql += " AND s.taskOrderStatus = 'WAIT_TAKING' ";
            //判断非指派单（有区域的任务单判断人员是否在区域内 + 无区域的维修单）
            jpql += " AND (( s.assign = false AND ( s.taskArea IS NULL ";
            if (CollectionUtils.isNotEmpty(areaIds)) {
                jpql += " OR  s.taskArea.id IN (" + StringUtils.strip(areaIds.toString(), "[]") + ")";
            }

            //判断指派单（指派人的工单 + 无区域指派岗位的工单 + 有区域有岗位的工单）
            jpql += ")) OR ( s.assign = true AND (" + StringConverters.null2Long(userId) + " in elements(s.taskAssignUsers) ";
            if (StringUtils.isNotBlank(positionId)) {
                jpql += " OR (s.taskArea is null AND " + StringConverters.null2Long(positionId) + " in elements(s.taskAssignPositions))";
                if (CollectionUtils.isNotEmpty(areaIds)) {
                    jpql += " OR (s.taskArea is not null AND s.taskArea.id IN (" + StringUtils.strip(areaIds.toString(), "[]") + ") AND " + StringConverters.null2Long(positionId) + " in elements(s.taskAssignPositions)) ";
                }
            }
            jpql += " ))) ";
        }
        //未完成（人员为接单人）
        if ("2".equals(status)){
            jpql += " AND s.taskOrderStatus IN ('WAIT_PRESENCE','UNFINISHED','REJECTED') ";
            if (StringUtils.isNotBlank(date)) {
                jpql += " and s.receiveTime <='" + date + "'";
            }
            //非领导查询语句
            // 接单人为自己
            if (!leader) {
                jpql += " AND s.receiveUser.id = " + userId + " ";
            }
            //领导查询语句
            if (leader) {
                //接单人不是自己 部门下及下级部门
                jpql += " AND (s.receiveUser.id = " + userId + "  " +
                        "OR (s.receiveUser.id != " + userId + " AND  exists (SELECT rs FROM s.receiveUser.systemUserOrganizationSet rs WHERE rs.organization.parentIds LIKE '" + organization.getParentIds() + "%')))";
            }
        }
        // 审核中
        if ("3".equals(status)){
            if (organization == null) {
                return result;
            }
            jpql += " AND s.taskOrderStatus IN ('IN_AUDITING') ";

            //非领导查询语句  ** 后改逻辑，沿用上面 》未完成 的逻辑
            // 接单人为自己
            if (!leader) {
                jpql += " AND s.receiveUser.id = " + userId + " ";
            }
            //领导查询语句
            if (leader) {
                //接单人不是自己 部门下及下级部门
                jpql += " AND (s.receiveUser.id = " + userId + "  " +
                        "OR (s.receiveUser.id != " + userId + " AND  exists (SELECT rs FROM s.receiveUser.systemUserOrganizationSet rs WHERE rs.organization.parentIds LIKE '" + organization.getParentIds() + "%')))";
            }

//            jpql += " AND s.taskOrderStatus = 'IN_AUDITING' ";
//            //人员在审核节点中 部门 - 人员 部门 - 岗位
//            jpql += " AND (s.receiveUser.id = " + userId + " OR (s.auditOrganization.id = " + organization.getId() + " AND ( s.auditUser.id = " + userId +" OR  s.auditPosition.id = " + positionId + " ) ";
//
//            //领导查询语句
//            if(leader){
//                jpql=jpql+ "OR (s.receiveUser.id != " + userId + " AND  exists (SELECT rs FROM s.receiveUser.systemUserOrganizationSet rs WHERE rs.organization.parentIds LIKE '" + organization.getParentIds() + "%'))";
//            }
//
//            jpql += " )) ";


        }

        // 已完成
        if ("4".equals(status)){
            jpql += " AND s.taskOrderStatus IN ('CANCELED','COMPLETED') ";
            //非领导查询语句
            /**
             * 接单人为自己
             */
            if (!leader) {
                jpql += " AND s.receiveUser.id = " + userId + " ";
            }
            if (leader) {
                //接单人不是自己 部门下及下级部门
                jpql += " AND (s.receiveUser.id = " + userId + "  " +
                        "OR (s.receiveUser.id != " + userId + " AND  exists (SELECT rs FROM s.receiveUser.systemUserOrganizationSet rs WHERE rs.organization.parentIds LIKE '" + organization.getParentIds() + "%'))) ";
            }
        }

        if (StringUtils.isNotBlank(searchParam)) {
            jpql += " AND (s.serial like '%" + searchParam + "%' OR s.orderName like '%" + searchParam + "%' OR s.taskContent like '%" + searchParam + "%') ";
        }

        // 排序
        if ("2".equals(status) ) {
//            jpql += " ORDER BY s.receiveTime DESC";
            jpql += " ORDER BY s.createDate DESC ";
        } else if ("3".equals(status)) {
            // 审批排序，按照更新时间排
            jpql += " ORDER BY s.updateDate DESC";
        } else {
            jpql += " ORDER BY s.createDate DESC ";
        }

        TypedQuery<TaskOrder> resultQuery = this.entityManager.createQuery(jpql, TaskOrder.class);
        int records = resultQuery.getResultList().size();
        if (index > 0 && size > 0) {
            int minLimit = size * (index - 1);
            int maxLimit = size;
            resultQuery.setFirstResult(minLimit).setMaxResults(maxLimit);
        }
        List<TaskOrder> resultList = resultQuery.getResultList();

        JSONArray rows = new JSONArray();
        for (TaskOrder taskOrder : resultList) {
            //标签设置
            Date now = new Date();
            JSONArray tags = new JSONArray();
            if (Objects.nonNull(taskOrder.getRequireFinishTime())){
                if (now.getTime() > taskOrder.getRequireFinishTime().getTime()) {
                    tags.add(tagObject("逾期", "full-orange"));
                }
            }

            if (taskOrder.isAssign()) {
                tags.add(tagObject("被指派", "blue"));
            }

            if(TaskOrderStatusEnum.IN_AUDITING.equals(taskOrder.getTaskOrderStatus())){
                tags.add(tagObject(NumberUtil.convert(taskOrder.getAuditLevel() + 1) + "审", "blue"));
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("createDate", DateTimeUtils.format(taskOrder.getCreateDate(), DateTimeUtils.format(taskOrder.getCreateDate(), "yy-MM-dd HH:mm")));
            jsonObject.put("taskContent", StringConverters.null2String(taskOrder.getTaskContent()));
            jsonObject.put("taskAddress", StringConverters.null2String(taskOrder.getTaskAddress()));
            jsonObject.put("orderStatus", taskOrder.getTaskOrderStatus().getName());
            jsonObject.put("serial", taskOrder.getSerial());
            jsonObject.put("orderTypeName", taskOrder.getOrderType() == null ? "" : taskOrder.getOrderType().getPropertyName());
            jsonObject.put("createUser", taskOrder.getCreateUser() == null ? "" : taskOrder.getCreateUser().getUserName());
            jsonObject.put("receiveUser", taskOrder.getReceiveUser() == null ? "" : taskOrder.getReceiveUser().getUserName());
            jsonObject.put("id", taskOrder.getId());
            jsonObject.put("tags", tags);

            rows.add(jsonObject);
        }
        result.put("rows", rows);
        result.put("records", records);

        return result;
    }

    private JSONObject tagObject(String name, String color) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("color", color);
        return jsonObject;
    }

    public List<SystemUser> confirmSendUser(Enterprise enterprise, Position position, Organization organization, SystemUser systemUser) {
        String jpql = "SELECT s FROM SystemUser s  WHERE 1 = 1 " +
                "AND s.deleteStatus = false " +
                "AND s.operationRole = 'common' " +
                "AND " + StringConverters.null2Long(enterprise.getId()) + " in elements(s.enterpriseSet) ";
        if (organization != null) {
            jpql += "AND exists (SELECT ss FROM s.systemUserOrganizationSet ss WHERE ss.organization.id = " + StringConverters.null2Long(organization.getId()) + ") ";
        }
        if (position != null) {
            jpql += "AND " + position.getId() + " in elements(s.positionSet) ";
        }
        if (systemUser != null) {
            jpql += "AND s.id = " + systemUser.getId() + " ";
        }
        TypedQuery<SystemUser> resultQuery = this.entityManager.createQuery(jpql, SystemUser.class);
        return resultQuery.getResultList();
    }

}
